<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: '配置客服',
			size: '90%'
		}"
		@confirm="setCusConfig"
		@close="close"
	>
		<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
			<cl-pagefull @resize="onResize">
				<template #head>
					<el-row type="flex">
						<cl-filter-group v-model="search">
							<cl-filter label="所属事业部">
								<cl-select
									v-model="search.biz_id"
									placeholder="请选择"
									filterable
									@change="changeBiz"
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="部门">
								<cl-cascader
									clearable
									v-model="search.dept_ids"
									:options="deptList"
									collapse-tags
									style="min-width: 250px"
									:props="{
										multiple: true,
										value: 'dept_id',
										label: 'dept_name'
									}"
									filterable
								/>
								<!-- <cl-select v-model="search.dept_id" placeholder="请选择" filterable>
									<el-option
										v-for="item in deptList"
										:key="item.dept_id"
										:label="item.dept_name"
										:value="item.dept_id"
									/>
								</cl-select> -->
							</cl-filter>
							<cl-filter label="客服">
								<cl-select
									v-model="search.users"
									placeholder="请选择"
									filterable
									clearable
									multiple
									collapse-tags
									@change="changeUsers"
								>
									<el-option
										v-for="item in list"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</cl-filter>
						</cl-filter-group>
					</el-row>
				</template>
				<!-- <zm-table v-bind="table" ref="table" v-loading="loading">
					<cl-empty slot="empty" />
					<template #column-setting_deploy="{ scope: { row } }">
						<el-button type="primary" plain @click="setDeploy(row)"> 配置 </el-button>
					</template>
					<template
						v-for="item in contactTypeList"
						#[`column-${item.type}_check`]="{ scope: { row } }"
					>
						<el-checkbox
							:label="row.wechat_type_data[item.value]"
							v-model="setCusCheck"
							:key="item.value"
							:disabled="
								row.wechat_type_data[item.value]
									? row.wechat_type_data[item.value].type_value
										? false
										: true
									: false
							"
						>
							{{
								row.wechat_type_data[item.value]
									? row.wechat_type_data[item.value].type_value
									: ""
							}}
						</el-checkbox>
					</template>
				</zm-table> -->
				<cl-data-table
					ref="table"
					id="shopDayInfo"
					v-bind="table"
					:page.sync="table.page"
					:limit.sync="table.limit"
					:loading="loading"
					@page-change="_tableSpanMethod"
					@limit-change="_tableSpanMethod"
				>
					<cl-empty slot="empty" />
					<template #column-setting_deploy="{ scope: { row } }">
						<el-button type="primary" plain @click="setDeploy(row)"> 配置 </el-button>
					</template>
					<template
						v-for="item in contactTypeList"
						#[`column-${item.type}_check`]="{ scope: { row } }"
					>
						<div class="select-wrap" :key="`${item.type_value}${item.type_name}`">
							<!-- 企业微信码-加微号 -->
							<div class="select-wrap_more" v-if="item.value == 5 && row.wxk && row.wxk.length > 1 && getWechatTypeStatus(row.wechat_type_data[item.value], item.value)" @click="selectMultiple(row.wechat_type_data[item.value], row)">
								<span>展开</span>
								<i class="iconfont el-icon-arrow-down"></i>
							</div>
						<el-checkbox-group
							:key="item.value"
							:disabled="!getWechatTypeStatus(row.wechat_type_data[item.value], item.value)"
							v-model="setCusCheck"
						>
						<!-- row.wechat_type_data[item.value]
										? row.wechat_type_data[item.value].type_value
										: "" -->
							<el-checkbox :label="item.value == 5 ? row.wechat_type_data[item.value].type_value[0] : row.wechat_type_data[item.value]">
								{{
									getWechatTypeValue(row.wechat_type_data[item.value], item.value)
								}}
							</el-checkbox>
						</el-checkbox-group>
						</div>
					</template>
				</cl-data-table>
			</cl-pagefull>
		</cl-crud>
		<behavior-config ref="behaviorConfig" @confirm="refresh" />
		<template #left-footer>
			<el-form
				class="cus-config"
				ref="form"
				:model="form"
				:rules="rules"
				inline
				:show-message="false"
				status-icon
			>
			<el-form-item label="客服组ID" prop="pool_id">
					<div class="flex">
						<el-input
							v-model="form.pool_id"
							placeholder="请输入客服组ID"
							style="width: 150px"
							class="mr-1"
						/>
						<el-button type="primary" @click="setCusConfig('pool_id')">
							确认
						</el-button>
					</div>
				</el-form-item>
				<el-form-item label="落地页ID" prop="land_id">
					<div class="flex">
						<el-input
							v-model="form.land_id"
							placeholder="请输入落地页ID"
							style="width: 150px"
							class="mr-1"
						/>
						<el-button type="primary" @click="setCusConfig('land_id')">
							确认
						</el-button>
					</div>
				</el-form-item>
				<!-- <el-form-item label="类型" prop="type">
					<cl-select v-model="form.type" style="width:100px;">
						<el-option :value="1" label="落地页" />
						<el-option :value="2" label="城市" />
					</cl-select>
				</el-form-item> -->
				<!-- <el-form-item label="城市ID" prop="city_id">
					<div class="flex">
						<el-input
							v-model="form.city_id"
							placeholder="请输入城市ID"
							style="width: 150px"
							class="mr-1"
						/>
						<el-button type="primary" @click="setCusConfig('city_id')">
							确认
						</el-button>
					</div>
				</el-form-item> -->
				<el-form-item label="公众号ID" prop="account_id">
					<div class="flex">
						<el-input
							v-model="form.account_id"
							placeholder="请输入公众号ID"
							style="width: 150px"
							class="mr-1"
						/>
						<el-button type="primary" @click="setCusConfig('account_id')">
							确认
						</el-button>
					</div>
				</el-form-item>
			</el-form>
		</template>
		<bind-multiple-wechat ref="bindMultipleWechat" :selArr.sync="setCusCheck"></bind-multiple-wechat>
	</cl-drawer>
</template>
<script>
import constant from "@/constant";
import BehaviorConfig from "./behavior-config";
import bindMultipleWechat from "./bind-multiple-wechat"
import { get } from "lodash";
import { delEmptyChildren, uniqBy, flatten } from "@/utils";

export default {
	inject: ["parent"],
	components: {
		BehaviorConfig,
		bindMultipleWechat
	},
	data() {
		return {
			contactTypeList: constant.CONTACT_TYPE,
			loading: false,
			form: {
				land_id: "",
				city_id: "",
				account_id: "",
				pool_id: ""
			},
			rules: {
				land_id: [{ required: true, message: "请输入落地页ID" }],
				city_id: [{ required: true, message: "请输入城市ID" }],
				account_id: [{ required: true, message: "请输入公众号ID" }],
				pool_id: [{ required: true, message: "请输入客服组ID" }]
			},
			saving: false,
			// 表格配置
			table: {
				"context-menu": ["refresh"],
				page: 1,
				limit: 20,
				data: [],
				autoPage: true,
				full: true,
				showSummary: true,
				spanMethod: this.tableSpanMethod,
				summaryMethod: () => {
					return this.summariesArr;
				},
				props: {
					spanMethod: this.tableSpanMethod,
					maxHeight: 500,
					showSummary: true,
					summaryMethod: () => {
						return this.summariesArr;
					}
				},
				columns: [
					// {
					// 	type: "index",
					// 	label: "序号",
					// 	width: 50,
					// 	fixed: true,
					// 	index: (index) => {
					// 		const { page, limit } = this.table;
					// 		return (page - 1) * limit + index + 1;
					// 	}
					// },
					{ label: "序号", prop: "index", minWidth: 50, fixed: true },
					{
						label: "部门",
						prop: "dep_name",
						minWidth: 100,
						fixed: true,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "姓名",
						prop: "user_name",
						minWidth: 90,
						fixed: true,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "行为配置(每日)",
						minWidth: 100,
						prop: "setting",
						children: [
							{ label: "总行为数", minWidth: 80, prop: "setting.ad_copy_total" },
							{ label: "轮循频率", minWidth: 80, prop: "setting.ad_copy_one" },
							{
								label: "定金单价",
								minWidth: 80,
								prop: "setting.ad_deposit_unit_price"
							},
							{ label: "配置", minWidth: 90, prop: "setting_deploy" },
							{ label: "开关", minWidth: 50, prop: "ad_close_date_desc" },
							{ label: "班次", minWidth: 50, prop: "banci_desc" }
						]
					}
				]
			},

			// 表格数据
			summariesArr: [],
			list: [],
			tableHeight: 500,
			deptList: [], //部门列表
			setCusCheck: [],
			search: {
				biz_id: "",
				dept_ids: [],
				users: []
			},
			init: true
		};
	},

	created() {
		this.search.biz_id = this.getCurrBiz();
		this.contactTypeList.forEach((v, i) => {
			if (v.value == 99) return;
			this.table.columns.push({
				label: v.label.replace("号", ""),
				minWidth: 120,
				prop: v.type,
				children: [
					{
						label: "选择",
						minWidth: 200,
						prop: v.type + "_check",
						val: v.value + "",
						align: "left",
						showOverflowTooltip: true
					},
					// {
					// 	label: "行为",
					// 	minWidth: 50,
					// 	prop: `wechat_type_data.${v.value}.copy`
					// },
					{
						label: "加微",
						minWidth: 50,
						prop: `wechat_type_data.${v.value}.jiawei`
					},
					{
						label: "落地页",
						minWidth: 70,
						prop: `wechat_type_data.${v.value}.ad_ldy`
					},
					{
						label: "城市",
						minWidth: 50,
						prop: `wechat_type_data.${v.value}.ad_city`
					},
					{
						label: "公众号",
						minWidth: 70,
						prop: `wechat_type_data.${v.value}.ad_gzh`
					}
				]
			});
		});
	},
	methods: {
		onResize(h) {
			this.table.props.maxHeight = h;
		},
		open() {
			this.$refs.drawer.create(() => {
				this.search.biz_id = this.getCurrBiz();
				this.init = false;
				this.changeBiz();
				// this.refresh();
			});
		},
		close() {
			this.resetCusConfig();
			this.list = [];
			this.table.data = [];
		},
		async changeBiz() {
			this.search.dept_ids = [];
			this.search.users = [];
			const { biz_id } = this.search;
			const data = await this.$service.ad.getCusDept({ biz_id });
			this.deptList = delEmptyChildren(data) || [];
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.ad)
				.set("dict", {
					api: { page: "cusList" }
				})
				.done();
			app.refresh();
		},
		async onRefresh(params, { next, render, done }) {
			if (this.init) {
				return done();
			}
			this.loading = true;
			let query = {
				...params,
				...this.search
			};
			const data = await next(query).done(() => {
				this.loading = false;
			});
			let list = uniqBy(data, "user_id");
			this.list = list;

			this._tableSpanMethod()
			this.changeUsers(query.users);

			render(list);
			this.$nextTick(() => {
				this.$refs.table && this.$refs.table?.doLayout?.();
			});
		},
		// crud刷新
		refresh() {
			this.$refs.crud.refresh({ page: 1, ...this.search });
		},
		_tableSpanMethod() {
			const startIndex = (this.table.page - 1) * this.table.limit
			const endIndex = this.table.page * this.table.limit

			const _list = JSON.parse(JSON.stringify(this.list))
			const list = _list.splice(startIndex, endIndex)
			let arr = [];
			let num;
			for (let i = 0; i < list.length; i++) {
				if (i === 0) {
					arr.push(1);
					num = 0;
				} else {
					if (list[i].dept_id === list[i - 1].dept_id) {
						arr[num] += 1;
						arr.push(0);
					} else {
						arr.push(1);
						num = i;
					}
				}
			}

			this.tableSpanArr = arr
		},
		// 合并单元格
		tableSpanMethod({ rowIndex, columnIndex }) {
			// 第一列
			if (columnIndex === 1) {
				const _row = this.tableSpanArr[rowIndex];
				const _col = _row > 0 ? 1 : 0;
				return {
					rowspan: _row,
					colspan: _col
				};
			}
		},
		// 配置客服table合计
		getSummaries({ columns, data }) {
			let ignore = ["dep_name", "user_name", "setting_deploy", "ad_close_date_desc"];
			this.contactTypeList.forEach(v => {
				ignore.push(v.type + "_check");
			});
			let moneyKeys = [
				"statistics.month.deposit_unit_price",
				"setting.ad_deposit_unit_price"
			];
			let statisticsDayJiawei = 0;
			let statisticsDayDeposit = 0;
			const newArr = columns.map((column, index) => {
				if (index === 0) {
					return "合计";
				}
				let prop = column.prop;
				if (ignore.includes(prop) || !prop) return "";
				if (prop == "statistics.month.deposit_rate") {
					let statisticsMonthJiawei = data
						.map(item => Number(get(item, "statistics.month.jiawei")))
						.reduce((prev, curr) => {
							const value = Number(curr);
							if (!isNaN(value)) {
								return prev + curr;
							}
							return prev;
						}, 0);
					let statisticsMonthDeposit = data
						.map(item => Number(get(item, "statistics.month.deposit")))
						.reduce((prev, curr) => {
							const value = Number(curr);
							if (!isNaN(value)) {
								return prev + curr;
							}
							return prev;
						}, 0);
					let monthDepositRate = statisticsMonthDeposit / statisticsMonthJiawei;
					if (!monthDepositRate) return "0%";
					return `${(monthDepositRate * 100 || 0).toFixed(2)}%`;
				}
				let isRatio = column.label.includes("率") && prop != "setting.ad_copy_one";

				const values = data.map(item => Number(get(item, prop)));
				let sum = values.reduce((prev, curr) => {
					const value = Number(curr);
					if (!isNaN(value)) {
						return prev + curr;
					}
					return prev;
				}, 0);
				if (prop == "statistics.day.jiawei") {
					statisticsDayJiawei = sum;
				}
				if (prop == "statistics.day.deposit") {
					statisticsDayDeposit = sum;
				}
				if (prop == "statistics.day.deposit_rate") {
					let dayDepositRate = statisticsDayDeposit / statisticsDayJiawei;
					if (!dayDepositRate) return "0%";
					return `${(dayDepositRate * 100 || 0).toFixed(2)}%`;
				}
				if (isRatio) {
					return this.toFixed(sum) + "%";
				}
				if (moneyKeys.includes(prop)) {
					return "￥" + this.toFixed(sum);
				}
				return this.toFixed(sum);
			});

			this.summariesArr = newArr;
			return newArr;
		},
		// 客服选择
		changeUsers(vals) {
			this.table.page = 1;
			let list = this.list;
			if (vals.length > 0) {
				list = this.list.filter(v => vals.includes(v.user_id));
			}
			this.table.data = list.map((v, i) => ({
				...v,
				index: i + 1
			}));
			this.getSummaries({ columns: flatten(this.table.columns), data: list });
		},
		// 行为配置
		setDeploy(row) {
			this.$refs.behaviorConfig.open(row);
		},
		resetCusConfig() {
			this.saving = false;
			this.search.dept_ids = [];
			this.setCusCheck = [];
			this.$refs.form.resetFields();
		},
		// 添加类型
		setCusConfig(field) {
			this.$refs.form.validateField(field, async msg => {
				this.$message.closeAll();
				if (msg) {
					this.$message.warning(msg);
					return;
				}
				const { biz_id } = this.search;
				const { land_id, city_id, account_id, pool_id } = this.form;
				let type = field === "land_id" ? 1 : field === "city_id" ? 2 : field === "account_id" ? 3 : 4;
				let form = {
					biz_id,
					id: type == 1 ? land_id : type == 2 ? city_id : type == 3 ? account_id : pool_id,
					type,
					chk_value: this.setCusCheck.map(v => {
						const text = v.content ?  `${v.user_id}-5-${v.id}` : `${v.user_id}-${v.type_key}`
						return text
					}).join()
				};
				await this.$service.ad.cusSet(form).finally(() => {
					this.saving = false;
				});
				this.$message.success("操作成功");
				this.resetCusConfig();
				this.parent.refresh();
				// this.refresh();
			});
			// this.$refs.form.validate(async (valid, errors) => {
			// 	this.showFormErr(errors);
			// 	if (!valid) return;
			// 	const { biz_id } = this.search;
			// 	let form = {
			// 		...this.form,
			// 		biz_id,
			// 		// type: 1,
			// 		chk_value: this.setCusCheck.map(v => `${v.user_id}-${v.type_key}`).join()
			// 	};
			// 	await this.$service.ad.cusSet(form).finally(() => {
			// 		this.saving = false;
			// 	});
			// 	this.parent.refresh();
			// 	this.$message.success("操作成功");
			// 	this.resetCusConfig();
			// 	this.refresh();
			// });
		},
		// 选择多个加微号
		selectMultiple(row, item) {
			this.$refs.bindMultipleWechat.open(row, item.user_name)
		},
		// 获取状态
		getWechatTypeStatus(row, type) {
			if (!row) return false

			let status = false
			if (type == 5) {
				// 如果是企业微信的时候
				status = row.type_value?.length > 0 ? true : false
			} else {
				status = row.type_value ? true : false
			}
			return status
		},
		getWechatTypeValue(row, type) {
			if (!row) return ''

			let text = ''
			if (type == 5) {
				// 如果是企业微信的时候
				// text = row?.type_value?.map(e => e.content).join(',') ?? ''
				text = row?.type_value[0]?.content ?? ''
			} else {
				text = row.type_value
			}
			return text
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep .el-table th {
	border-right: 1px solid #EBEEF5 !important;
}
.cus-config {
	::v-deep .el-form-item--mini.el-form-item {
		margin-bottom: 0;
	}
}
.select-wrap {
	display: flex;
	align-items: center;
	&_more {
		margin-right: 8px;
		color: $primary;
		cursor: pointer;
		.iconfont {
			margin-left: 2px;
		}
	}
}
</style>
